<!-- 区间站点树形公共组件 -->
<template>
	<view class="hwq-content g-tit">
		<navBar @click="goBack">
			<template slot="center">
				<text style="font-size: 36rpx;font-weight: bold;position: relative;">{{ titleName }}</text>
				<view class="total-color"
					v-if="compoType === 'dsh' || compoType === 'wx' || compoType === 'wxsh' || compoType === 'disease_review'">
					{{ getTotalNum }}
				</view>
			</template>
		</navBar>
		<searchCom class="search-input pos" v-model="keyword" style="margin-top: 120rpx;" @enter="determine"
			@change="determine"></searchCom>
		<scroll-view scroll-y="true" class="hwq-scroll-box hwq-is-search wx">
			<template v-for="item1 in treeData">
				<view class="item-box" :key="item1.id" @click="clickItem(item1.id, 0)">
					<view>{{ item1.name || "" }}</view>
					<view class="ico-box">
						<u-icon :name="showItem(item1.id, 0) ? 'arrow-down' : 'arrow-right'" color="#A7AEBD" size="28"
							:customStyle="{ transform: 'scale(.8)' }"></u-icon>
					</view>
				</view>
				<template v-for="item2 in item1.list" v-if="showItem(item1.id, 0)">
					<view class="item-box item-box-area" :key="item2.id" @click="clickItem(item1.id + '-' + item2.id)">
						<view>{{ `${item2.name}${item2.branchLineName ? '(' + item2.branchLineName + ')' : ''}`  || "" }}</view>
						<view class="ico-box">
							<u-icon :name="showItem(item2.id, 1) ? 'arrow-down' : 'arrow-right'" color="#A7AEBD" size="28">
							</u-icon>
						</view>
					</view>
					<template v-for="item3 in item2.list" v-if="showItem(item2.id, 1)">
						<view class="item-box item-box-point" :key="item3.id" @click="clickItem(item1.id + '-'+ item2.id + '-' + item3.id)">
							<view>{{ item3.name  || "" }}</view>
							<view class="ico-box">
								<u-icon :name="showItem(item3.id, 2) ? 'arrow-down' : 'arrow-right'" color="#A7AEBD" size="28">
								</u-icon>
							</view>
						</view>
						<template  v-if="showItem(item3.id,2)">
							 <!-- + Math.random() -->
							<view class="item-box item-box-point" style="padding-left: 80rpx;" v-for="item4 in item3.list" :key="item4.id">
								<view class="stip">{{ item4.name || "" }}</view>
								<view v-if="compoType === 'inspect'"> 
									<!-- 巡检状态（0开始，1结束） -->
									<view class="item-box-point-button" v-if="item4.type == 0">
										<u-button color="#2F80ED" class="custom-style" size="normal" text="开始"
											@click="staCtnEnd(item2, item3, item4,item1, 'sta')"></u-button>
									</view>
									<view class="item-box-point-button" v-if="item4.type == 1">
										<u-button color="rgb(10, 185, 156)" class="custom-style" size="normal"
											@click="staCtnEnd(item2, item3, item4,item1, 'ctn')" text="继续"></u-button>
											<!-- #ifdef MP-WEIXIN -->
												<view style="width: 40rpx;"></view>
											<!-- #endif -->
										<u-button type="error" class="custom-style" size="normal" text="结束"
											@click="staCtnEnd(item2, item3, item4,item1, 'end')" :disabled="btnloading"></u-button>
									</view>
						
								</view>
								<view class="item-box-point-button" v-if="compoType === 'disease_dispatch'">
									<u-button color="#2F80ED" class="custom-style" size="normal" text="未派单"
										@click="staCtnEnd(item2, item3, item4,item1, 'dispatchOrder')"></u-button>
									<view class="num-color">{{ item4.amount }}</view>
								</view>
								<view class="item-box-point-button" v-if="compoType === 'disease_review'">
									<u-button color="#2F80ED" class="custom-style" size="normal" text="待审核"
										@click="staCtnEnd(item2, item3, item4,item1, 'dsh')"></u-button>
									<view class="num-color">{{ item4.amount }}</view>
								</view>
								<view class="item-box-point-button" v-if="compoType === 'wx'">
									<u-button color="#F99C34" class="custom-style" size="normal" text="未修复"
										@click="staCtnEnd(item2, item3, item4, item1,'wxf')"></u-button>
									<view class="num-color">{{ item4.amount ? item4.amount : 0 }}</view>
								</view>
								<view class="item-box-point-button" v-if="compoType === 'wxsh'">
									<u-button color="#2F80ED" class="custom-style" size="normal" text="待审核"
										@click="staCtnEnd(item2, item3, item4,item1, 'wxsh')"></u-button>
									<view class="num-color">{{ item4.amount ? item4.amount : 0 }}</view>
								</view>
							</view>
						</template>
					</template>
					
				</template>
			</template>
		</scroll-view>
	<u-loading-page :loading="isLoading"  loading-text="缓存数据中·····" :color="'#3b9cff'" :bgColor="'rgba(0, 0, 0, 0.7)'"></u-loading-page>
	</view>
</template>

<script>
import searchCom from "@/components/searchCom.vue"
import mixins from '@/utils/mixins.js'
import {
	inspectLogUpdateState, //更改状态
} from '@/api/engineeringMaintenance/engineeringMaintenance.js'
import { BS, BSM } from "@/session/index.js"
import {doGet,doSave,doDelete, ingoreNetGet} from "@/utils/offline/sqlite/index.js";
// //巡检的所有接口
import * as XUNJIAN from '@/api/engineeringMaintenance/engineeringMaintenance.js'
// #ifdef APP-PLUS
import {before} from "./beforeOffline.js"
import {networkOnline} from "@/utils/offline/listener.js"
import { DB } from "@/utils/offline/sqlite/dbinit.js";
import {clearLoaclDBTable} from "@/utils/offline/task/siteInspection.js"
// #endif

export default {
	name: 'onSiteInspection',
	mixins: [mixins],
	props: {
		titleName: {
			type: String,
			default: '巡检'
		},
		//工程维保类型(字典表里面配置的)
		compoType: {
			type: String,
			default: 'inspect'
		},
		treeData: {
			type: Array,
			default: () => { return [] }
		},
		// startId: {
		// 	type: String,
		// 	default:'',
		// }
	},
	mounted() {
		uni.$on('listenerClickStartBtn', res => {
			this.startId = res
			console.log(res,'监听-----------');
		})
	},
	computed: {
		//标题总数
		getTotalNum() {			
			return this.treeData
				.map(pm => pm.list).flat()
				.map(line => line.list).flat()
				.map(station => station.list).flat()
				.filter(i => i.amount > 0).map(i => i.amount)
				.reduce((p, n) => p + n, 0)
		}
	},
	data() {
		return {
			keyword: null,
			activeItem: "",
			//离线方面的东西
			sqlite: null,
			DB: null,
			isLoading:false,
			startId: uni.getStorageSync('lineData') &&  JSON.parse(uni.getStorageSync('lineData')).lineSiteSectionId, 		//记录的缓存线路的id
			btnloading:false
		}
	},
	components: {
		searchCom
	},
	methods: {
		//点击开始巡检
		  async staCtnEnd(obj1, obj2, obj3, obj4,state) {
			// console.log(obj1, obj2, obj3, obj4,state, '166行');
			const lineObj = {
				branchLineName:obj1.branchLineName || '',
				lineId: obj1.id,
				lineName: obj1.name,
				lineSiteSectionId: obj3.id,
				lineSiteSectionName: obj3.name,
				mileage:obj3.mileage || 'K',
				lineSiteSectionType: obj2.id,
				pmId:obj4.id,
				pmName:obj4.name
			}
			// console.log(lineObj);    
			BSM[BS.session1].lineObj = lineObj
			// #ifdef APP-PLUS
				if(!(!(await networkOnline()) && (state === 'ctn' || state === 'end'))) {
					uni.setStorageSync('lineData', JSON.stringify(lineObj))
					// uni.showModal({
					// 	title:`${await networkOnline()}判断`,
					// })
				}
			// #endif
			// #ifdef MP-WEIXIN || H5
				uni.setStorageSync('lineData', JSON.stringify(lineObj))
			// #endif
			let record_params = {
				lineId: obj1.id,
				lineName: obj1.name,
				lineSiteSectionId: obj3.id,
				lineSiteSectionType: obj2.id,
				lineSiteSectionName: obj3.name,
				mileage:obj3.mileage || 'K',
				pmId:obj4.id,
				pmName:obj4.name,
				inspectState: obj3.type == 1 ? 0 : 1
			}
			const title_params = {
				branchLineName:obj1.branchLineName || '',
				navTitle: obj1.name,
				siteTitle: obj2.name,
				subTitle: obj3.name,
				mileage:obj3.mileage || 'K',
				lineSiteSectionType: obj2.id,
			}
			
			
			if (state === 'sta') {
				uni.navigateTo({
					url: `/subpackage-enginner/pages/engineeringMaintenance/on_site_inspection/startPatrolInspection?recordParams=${JSON.stringify(record_params)}&titleParams=${JSON.stringify(title_params)}`
				})
			} else if (state === 'ctn') {
				//离线之前准备工作
				// #ifdef APP-PLUS
					// const cachedList = await DB.select(`select * from diseases`)
					// console.log(await DB.select(`select count(*) from diseases`),'病害数据');
					console.log(await networkOnline(),'网络状态');
					console.log(JSON.parse(uni.getStorageSync('lineData')),'存储的东西');
					//点击继续按钮时 处于离线状态并且无缓存数据 弹出提示
					if(!(await networkOnline())) {
						console.log(this.startId,'点击开始按钮的id',obj3.id);
						//离线状态下 点击继续按钮时判断  开始按钮是否已经缓存了数据
						if(this.startId != obj3.id) {
							uni.showToast({
							title:'当前无网络,无法继续',
							icon:"none",
							mask:true
							})
							return
						}
					}else{
						this.isLoading = true
						await before(lineObj, {
							projectId:uni.getStorageSync('isOwner')
						})
						this.startId = obj3.id
						this.isLoading = false	
					}

				// #endif
				uni.navigateTo({
					url: `/subpackage-enginner/pages/engineeringMaintenance/on_site_inspection/continueToPatrol?titleParams=${JSON.stringify(title_params)}`
				})
				
			} else if (state === 'end') {
				//当前为结束状态  点击后该区间按钮变为【开始】
				console.log('点击了结束按钮')
				this.btnloading = true
				this.$set(record_params, 'inspectState', 0)
				this.$set(record_params, 'id', obj3.amount)
				this.$set(record_params, 'inspectEndDate', new Date().getTime())
			// #ifdef APP-PLUS
				if(!(await networkOnline())) {
						uni.showToast({
						title:'当前无网络,无法继续',
						icon:"none",
						mask:true
						})
						this.btnloading = false
						return
				}				
			// #endif
				doSave(XUNJIAN.inspectLogUpdateState, record_params)
				.then(res => {
					if(!res.success) {
						return uni.showToast({
							title:'修改失败',
							icon:'none'
						})
					}
					this.btnloading = false
					// // #ifdef APP-PLUS
					// clearLoaclDBTable()
					// // #endif
					this.$emit('endEvent')
				})
			} else if (state === 'dispatchOrder') {
				uni.navigateTo({
					url: `/subpackage-enginner/pages/engineeringMaintenance/disease_dispatch/unDispatch?data=${JSON.stringify(lineObj)}`
				})
			} else if (state === 'dsh') {
				uni.navigateTo({
					url: `/subpackage-enginner/pages/engineeringMaintenance/disease_review/components/disReview?data=${JSON.stringify(lineObj)}`
				})
			} else if (state === 'wxf') {
				uni.navigateTo({
					url: `/subpackage-enginner/pages/engineeringMaintenance/repair/components/notRepaired?recordParams=${JSON.stringify(record_params)}&titleParams=${JSON.stringify(title_params)}`
				})
			} else if (state === 'wxsh') {
				uni.navigateTo({
					url: `/subpackage-enginner/pages/engineeringMaintenance/repair_check/components/maintenanceAudit?recordParams=${JSON.stringify(record_params)}&titleParams=${JSON.stringify(title_params)}`
				})
			}
		},
		showCount(str1){
			let index = str1.indexOf('-');
			let num = 0;
			while (index !== -1) {
				index = str1.indexOf('-', index + 1);
				num++;
			}
			return num
		},
		showItem(id, index = 0) {
			let arr = this.activeItem.split("-")
			return arr[index] == id
		},
		//点击菜单父选项
		clickItem(str) {
			// debugger
			if (str === this.activeItem && str.indexOf('-') !== -1) {
				if(this.showCount(str) === 1) {
					this.activeItem = str.split('-')[0]
				}else {
					this.activeItem = str.split('-')[0] + '-' + str.split('-')[1]
				}
				return
			}
			if (str === this.activeItem) {
				this.activeItem = ''
			} else {
				this.activeItem = String(str)
			}
		},
		/**
		 * 输入框值变化的时候
		 * @param {String} val
		 */
		searchChange(val) {
			this.$emit('searchChange', val)
		},
		determine(val) {
			this.$emit('determine', val)
		},
		goBack() {
			uni.switchTab({
				url:'/pages/homePage/homePage'
			})
		}
		
		
	}
}
</script>

<style lang="scss" scoped>
.g-tit {
	/* #ifdef MP-WEIXIN */
		padding-top: 200rpx;
	/* #endif */
	// top: -80rpx;
	// position: relative;
	.total-color {
		text-align: center;
		line-height: 28rpx;
		width: 28rpx;
		height: 28rpx;
		border-radius: 50%;
		background-color: #fe706c;
		color: #ffffff;
		margin-left: 20rpx;
		font-size: 10px;
		position: absolute;
		left: 440rpx;
		top: 20rpx;
	}

	.tit {
		position: absolute;
		top: 24rpx;
		left: 60%;
		z-index: 100;
		width: 40rpx;
		height: 40rpx;
		background: red;
		text-align: center;
		border-radius: 50%;
	}
}

.stip {
	overflow: hidden;
	text-overflow: ellipsis;
	white-space: nowrap;
	// width: 300rpx;
	width: auto;
}

.item-box {
	padding-top: 20rpx;
	padding-bottom: 20rpx;
	// height: 120rpx;
	display: flex;
	align-items: center;
	justify-content: space-between;
	margin: 0 30rpx;
	border-top: 2rpx solid #E2E5ED;

	&:first-child {
		border-top-width: 0;
	}

	.name {
		font-size: 36rpx;
		font-family: PingFang SC-Medium, PingFang SC;
		color: #445469;
		line-height: 120rpx;
		border-bottom: 2rpx solid #E2E5ED;
	}
}

.item-box-area {
	padding-left: 30rpx;
}

.item-box-point {
	padding-left: 60rpx;
}

.item-box-point-button {
	display: flex;
	align-items: center;
	position: relative;
	.custom-style {
		margin: 5rpx;
		height: 60rpx;
		width: 110rpx;
	}
	.num-color {
		position: absolute;
		font-weight: bold;
		margin-left: 18rpx;
		color: #ffffff;
		height: 40rpx;
		width: 40rpx;
		border-radius: 50%;
		line-height: 40rpx;
		text-align: center;
		background: #fe706c;
		left: 80rpx;
		bottom: 40rpx;
	}
}
/deep/ .hwq-scroll-box.hwq-is-search.wx {
	/* #ifdef MP-WEIXIN */
		height: calc(100% - 160rpx);
	/* #endif */
}
</style>
